<template>
  <scroll-view 
    class="discovery" 
    scroll-y 
    refresher-enabled
    :refresher-triggered="refreshing"
    @refresherrefresh="onRefresh"
  >
    <Weather ref="weatherRef" />
    <TravelRecommend ref="travelRef" />
  </scroll-view>
</template>

<script setup>
import { ref } from 'vue';
import Weather from '../commpoent/weather.vue';
import TravelRecommend from '../commpoent/travel-recommend.vue';

const weatherRef = ref(null);
const travelRef = ref(null);
const refreshing = ref(false);

// 处理下拉刷新
const onRefresh = async () => {
  refreshing.value = true;
  try {
    const promises = [];
    
    // 刷新天气数据
    if (weatherRef.value?.getWeatherData) {
      promises.push(weatherRef.value.getWeatherData());
    }
    
    // 刷新旅游推荐
    if (travelRef.value?.getRecommendation) {
      promises.push(travelRef.value.getRecommendation());
    }
    
    // 等待所有刷新完成
    await Promise.all(promises);
    
    // 提示刷新成功
    uni.showToast({
      title: '刷新成功',
      icon: 'success',
      duration: 2000
    });
  } catch (err) {
    console.error('刷新数据失败:', err);
    // 提示刷新失败
    uni.showToast({
      title: '刷新失败',
      icon: 'error',
      duration: 2000
    });
  } finally {
    refreshing.value = false;
  }
};

// 优化地理编码获取函数
const getAttractionsGeocode = async () => {
  try {
    const originalAttractions = [...attractions.value];
    const successfulAttractions = [];
    const failedNames = [];
    
    // 对每个景点进行地理编码查询
    for (let i = 0; i < originalAttractions.length; i++) {
      const attraction = originalAttractions[i];
      
      // 1. 基础清理
      let cleanName = attraction.name.trim();
      cleanName = cleanName.replace(/^\d{1,2}[:：]\d{2}[^a-zA-Z\u4e00-\u9fa5]*/, '');
      cleanName = cleanName.replace(/^(?:参观|游览|前往|到达|游玩|拜访|在|逛一逛)\s*/, '');
      cleanName = cleanName.replace(/(?:附近|内部|周边|广场购物)$/, '');
      
      if (cleanName.length > 15) cleanName = cleanName.substring(0, 15);
      
      // 2. 构建标准化地址
      // 优先提取地址中可能包含的区县等信息
      const districtMatch = cleanName.match(/(.+[区县市镇])/);
      const district = districtMatch ? districtMatch[1] : '';
      const remainingName = districtMatch ? cleanName.replace(districtMatch[1], '') : cleanName;
      
      // 构建遵循标准格式的地址
      let formattedAddress;
      if (district) {
        // 如果能提取到区县级别的信息，使用完整格式
        formattedAddress = `${city.value}${district}${remainingName}`;
      } else {
        // 否则直接使用城市+名称
        formattedAddress = `${city.value}${cleanName}`;
      }
      
      if (cleanName && cleanName.length >= 2) {
        try {
          const response = await getGeocode({
            address: formattedAddress,
            city: city.value
          });
          
          if (response.data && response.data.status === '1' && response.data.geocodes && response.data.geocodes.length > 0) {
            // 3. 多结果筛选逻辑
            let bestMatch = null;
            const geocodes = response.data.geocodes;
            
            if (geocodes.length === 1) {
              // 如果只有一个结果，直接使用
              bestMatch = geocodes[0];
            } else {
              // 多个结果时，根据相关度排序
              
              // 首先检查是否有精确匹配城市的结果
              const cityMatches = geocodes.filter(g => g.city === city.value);
              if (cityMatches.length > 0) {
                // 再检查是否包含景点名称
                const nameMatches = cityMatches.filter(g => 
                  g.formatted_address.includes(cleanName) || 
                  g.name.includes(cleanName)
                );
                
                if (nameMatches.length > 0) {
                  // 按地址级别排序 - 优先选择级别较高的(数字越小级别越高)
                  nameMatches.sort((a, b) => {
                    const levelA = parseInt(a.level || '0');
                    const levelB = parseInt(b.level || '0'); 
                    return levelA - levelB;
                  });
                  bestMatch = nameMatches[0];
                } else {
                  bestMatch = cityMatches[0];
                }
              } else {
                // 如果没有匹配城市的，选择第一个
                bestMatch = geocodes[0];
              }
            }
            
            const location = bestMatch.location;
            
            // 保存匹配结果
            successfulAttractions.push({
              ...attraction,
              name: cleanName,
              originalName: attraction.name,
              location: location,
              address: bestMatch.formatted_address,
              geocode: bestMatch
            });
          } else {
            console.error(`无法获取景点"${cleanName}"的地理编码`);
            failedNames.push(attraction.name);
          }
        } catch (queryErr) {
          console.error(`查询景点"${cleanName}"时出错:`, queryErr);
          failedNames.push(attraction.name);
        }
      } else {
        console.warn(`景点名称"${attraction.name}"无法提取有效关键词`);
        failedNames.push(attraction.name);
      }
      
      // 避免频繁请求
      await new Promise(resolve => setTimeout(resolve, 300));
    }
    
    if (successfulAttractions.length > 0) {
      attractions.value = successfulAttractions;
      if (failedNames.length > 0) {
        console.warn(`以下景点未能获取地理编码：${failedNames.join(', ')}`);
      }
      return true;
    } else {
      error.value = '无法获取任何景点的位置信息，请尝试手动输入';
      return false;
    }
  } catch (err) {
    console.error('获取地理编码失败:', err);
    error.value = '获取景点位置信息失败';
    return false;
  }
};
</script>

<style scoped lang="scss">
.discovery {
  height: 100vh;
  background-color: #f5f5f5;
}
</style>
